/*
 * @Author: lihaogn
 * @Date: 2021-12-18 11:20:58
 * @LastEditTime: 2021-12-21 10:22:44
 * @LastEditor: lihaogn
 * @Description: 角色 - service
 * @FilePath: \lix-admin-server\app\service\role.js
 */
const Service = require("egg").Service;
const commonUtils = require("../utils/commonUtils");

class RoleService extends Service {
  /**
   * @author: lihaogn
   * @Date: 2021-12-19 21:46:03
   * @description: 查询角色
   * @param {*}
   * @return {*}
   */
  async queryRoles() {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Role.findAll({
        include: {
          model: app.model.Permission,
          as: "permission",
          through: {
            attributes: [], // 不需要关联表中的数据
          },
        },
      });
      return res;
    } catch (err) {
      console.log("查询角色信息err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-19 22:22:59
   * @description: 新增角色
   * @param {*} req
   * @return {*}
   */
  async createRole(req) {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Role.create({
        id: commonUtils.getUUID(),
        name: req.name,
        description: req.description,
      });
      return res;
    } catch (err) {
      console.log("创建角色err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 01:02:47
   * @description: 修改角色
   * @param {*} id
   * @param {*} name
   * @param {*} description
   * @return {*}
   */
  async updateRole(id, { name, description }) {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Role.update(
        {
          name,
          description,
        },
        {
          where: { id },
        }
      );
      return res.length;
    } catch (err) {
      console.log("修改角色err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 22:39:05
   * @description: 修改角色的权限
   * @param {*} id - 角色的id
   * @param {*} keys - 分配给角色的权限id集合
   * @return {*}
   */
  async updateRolePermission(id, { keys }) {
    const { app } = this;
    try {
      const permissions = await app.model.Permission.findAll({
        where: { id: keys },
      });
      const role = await app.model.Role.findByPk(id);
      role.setPermission(permissions);
      return true;
    } catch (error) {
      console.log("修改角色权限err:", error);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 16:46:12
   * @description: 删除某个角色
   * @param {*} id
   * @return {*}
   */
  async deleteRole(id) {
    const { app } = this;

    try {
      const res = await app.model.Role.destroy({
        where: { id },
      });
      return res;
    } catch (error) {
      console.log("deleteRole err", error);
      return false;
    }
  }
}

module.exports = RoleService;
